import {
    updateQueue
} from './component';

/**
 * 
 * @param {*} dom 要绑定事件的dom元素
 * @param {*} eventType 事件类型
 * @param {*} handler 事件处理函数
 */
export function addEvent(dom, eventType, handler) {
    // store是自定义属性
    let store = dom.store || (dom.store = {}) //保证dom上有store属性，初始值是{}
    store[eventType] = handler //虽然没有给子dom绑定事件，但是事件处理函数还是保存在子dom上的store上
    // 从17版本开始，我们不在把事件委托给doc了，而是委托给root了
    if (!document[eventType]) {
        document[eventType] = dispatchEvent
    }
}
// 合成事件的统一处理函数
function dispatchEvent(event) {
    let {
        target,
        type
    } = event; //targe=button  type=click
    let eventType = `on${type}`; //
    // console.log('event',event)

    let syntheticEvent = createSyntheticEvent(event); //创建合成事件方法
    updateQueue.isBatchUpdate = true //事件函数先设置isBatchUpdate为ture
    // 在此我们要模拟react事件的冒泡
    while (target) {
        let {
            store
        } = target
        let handler = store && store[eventType]
        handler && handler(syntheticEvent)
        //在执行handler的过程中有可能会阻止冒泡
        if (syntheticEvent.isPropagationStopped) {
            break;
        }
        target = target.parentNode
    }
    updateQueue.isBatchUpdate = false
    updateQueue.batchUpdate()
}
/**
 *  为什么不把原生事件对象直接传给事件处理函数呢
 *  1.为了兼容性，像jq一样抹平浏览器差异
 *  2.
 * @param {*} nativeEvent 
 * @returns 
 */
function createSyntheticEvent(nativeEvent) {
    let syntheticEvent = {};
    for (let key in nativeEvent) { //把原生事件上的属性拷贝到合成事件对象上去
        syntheticEvent[key] = nativeEvent[key];
    }
    syntheticEvent.nativeEvent = nativeEvent;
    syntheticEvent.preventDefault = preventDefault;
    syntheticEvent.stopPropagation = stopPropagation;
    syntheticEvent.isDefaultPrevented = false; //preventDefault
    syntheticEvent.isPropagationStopped = false; //stopPropagation
    syntheticEvent.ikki = function () {
        console.log('Ikki你真帅')
    }
    return syntheticEvent
}
/**
 * 阻止默认事件
 */
function preventDefault(event) {
    if (!event) { //兼容IE
        window.event.returnValue = false;
    }
    // 标准浏览器
    if (event.preventDefault) {
        event.preventDefault()
    }
    this.isDefaultPrevented = true;
}

// 阻止冒泡(浏览器原生属性)
function stopPropagation() {
    const event = this.nativeEvent;
    if (event.stopPropagation) {
        event.stopPropagation();
    } else { //IE
        event.cancelBubble = true;
    }
    this.isPropagationStopped = true;
}